package com.cx.controller.wjr;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cx.pojo.*;
import com.cx.pojo.wjr.UserPage;
import com.cx.service.wjr.CourierService;
import com.cx.util.AppUtil;
import com.cx.util.wjr.GetDistance;
import com.cx.vo.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("courier")
public class CourierController {
    @Autowired
    CourierService courierService;
    @Autowired
    AlipayTradePagePayRequest alipayTradePagePayRequest;
    @Autowired
    AlipayClient alipayClient;

    @RequestMapping("courierLogin")
    @ResponseBody
    public ResponseResult courierLogin(Courier courier, Model model){
        ResponseResult responseResult = new ResponseResult();
        CourierExample courierExample = new CourierExample();
        courierExample.createCriteria().andCourierPhoneEqualTo(courier.getCourierPhone()).andCourierPasswordEqualTo(courier.getCourierPassword());
        List<Courier> courierList = courierService.selectLogin(courierExample);

        String start = courierList.get(0).getCourierProvince()+courierList.get(0).getCourierCity()+courierList.get(0).getCourierArea();
        String startLonLat = GetDistance.getLonLat(start);

        String[] location = startLonLat.split(",");
        courierList.get(0).setReservedFields1(location[0]);
        courierList.get(0).setReservedFields2(location[1]);


        if(courierList.size()>0){
            responseResult.setCode(1);
            responseResult.setData(courierList.get(0));
            responseResult.setMessage("登录成功");
            return responseResult;
        }
        responseResult.setCode(2);
        responseResult.setMessage("用户名或密码错误");
        return responseResult;
    }

    @RequestMapping("grabbing")
    @ResponseBody
    public ResponseResult grabbing(@RequestParam(defaultValue = "1")Integer pageNum,String id ,ResponseResult responseResult, UserPage userPage){
        CourierWorkExample courierWorkExample = new CourierWorkExample();
        CourierExample courierExample = new CourierExample();
        courierExample.createCriteria().andCourierPhoneEqualTo(id);
        Courier courier = courierService.selectCourierById(Integer.valueOf(id));

        String start = courier.getCourierProvince()+courier.getCourierCity()+courier.getCourierArea();
        String end = userPage.getSendProvince() + userPage.getSendCity() + userPage.getSendArea() + userPage.getSendAddress() + userPage.getSendDetail();
        String startLonLat = GetDistance.getLonLat(start);
        System.out.println(startLonLat);
        userPage.setCourierNum(Integer.valueOf(id));


        if(null != userPage.getStatus()){

            PageHelper.startPage(pageNum, 5);
            List<UserPage> userPages = courierService.selectGrabbing(userPage);
            PageInfo pageInfo = new PageInfo(userPages,5);
            responseResult.setData(pageInfo);

            responseResult.setCode(1);
            return responseResult;
        }
        responseResult.setCode(2);
        responseResult.setMessage("运输状态不能为空");
        return responseResult;
    }

    @RequestMapping("grabbingNew")
    @ResponseBody
    public ResponseResult grabbingNew(@RequestParam(defaultValue = "1")Integer pageNum,String id ,ResponseResult responseResult, UserPage userPage){
        System.out.println(id);
        CourierWorkExample courierWorkExample = new CourierWorkExample();
        CourierExample courierExample = new CourierExample();

        Courier courier = courierService.selectCourierById(Integer.valueOf(id));

        System.out.println(courier);

//        String start = courier.getCourierProvince()+courier.getCourierCity()+courier.getCourierArea();
        String end = userPage.getSendProvince() + userPage.getSendCity() + userPage.getSendArea() + userPage.getSendAddress() + userPage.getSendDetail();

        userPage.setStatus("已下单");
        List<UserPage> userPages = null;
        if(null != userPage.getStatus()){

            userPages = courierService.selectNew(userPage);

        }
        responseResult.setCode(1);
        responseResult.setData(userPages);
        return responseResult;
    }

    @RequestMapping("grabbingMap")
    @ResponseBody
    public ResponseResult grabbingMap(@RequestParam(defaultValue = "1")Integer pageNum,String id ,ResponseResult responseResult, UserPage userPage){
        CourierWorkExample courierWorkExample = new CourierWorkExample();
        System.out.println("map执行了");
        userPage.setStatus("已下单");
        CourierExample courierExample = new CourierExample();
        courierExample.createCriteria().andIdEqualTo(Integer.valueOf(id));
        List<Courier> courierList = courierService.selectLogin(courierExample);
        Courier courier = courierList.get(0);
        String start = courier.getCourierProvince()+courier.getCourierCity()+courier.getCourierArea();
        String startLonLat = GetDistance.getLonLat(start);

        List<UserPage> userPageReally = new ArrayList<>();
//        if(null != userPage.getStatus()){
            //PageHelper.startPage(pageNum, 5);
        userPage.setCourierNum(Integer.valueOf(id));
        List<UserPage> userPages = courierService.selectGrabbing(userPage);
            //PageInfo pageInfo = new PageInfo(userPages,5);
            for (UserPage userPageOne: userPages) {
                if(userPageOne.getLongitude()!=null){
                    userPageReally.add(userPageOne);
                }
            }

//        }
        responseResult.setData(userPageReally);
        responseResult.setCode(1);
        responseResult.setMessage("成功");
        return responseResult;
    }
    @RequestMapping("maptext")
    @ResponseBody
    public ResponseResult grabbingMap123(@RequestParam(defaultValue = "1")Integer pageNum,String id ,ResponseResult responseResult, UserPage userPage){
        long dis = GetDistance.getDistance("江苏省苏州市独墅湖创客汇","江苏省苏州市吴中区苏州长城汽车修理有限公司");
        responseResult.setData(1);
        responseResult.setCode(1);
        responseResult.setMessage("成功");
        return responseResult;
    }
    @RequestMapping("pageText")
    @ResponseBody
    public ResponseResult pageText(@RequestParam(defaultValue = "1")Integer pageNum,String id ,ResponseResult responseResult, UserPage userPage){
            List<String> strings = new ArrayList<>();
            strings.add("2");
            PageHelper.startPage(pageNum, 5);
            List<String> userPages = strings;
            PageInfo pageInfo = new PageInfo(userPages,5);
            responseResult.setData(pageInfo);
            responseResult.setCode(1);
            return responseResult;
    }

    @RequestMapping("courierInCome")
    @ResponseBody
    public ResponseResult courierInCome(String id,CourierWork courierWork){
        System.out.println(id);
        CourierWorkExample courierWorkExample = new CourierWorkExample();
        courierWorkExample.createCriteria().andCourierNumEqualTo(Integer.valueOf(id));
        List<CourierWork> courierList = courierService.courierInHowInCome(courierWorkExample);
        CourierWork courierWorkResult  = courierList.get(0);
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(1);
        responseResult.setMessage("查找成功");
        responseResult.setData(courierWorkResult.getCompleteAmount());

        return responseResult;

    }

    @RequestMapping("courierUpdate")
    @ResponseBody
    public ResponseResult updateUserPage(String id,String money,ResponseResult responseResult, UserPage userPage,PageExample pageExample,Page page){
        CourierWorkExample courierWorkExample = new CourierWorkExample();
        System.out.println("id====="+id);
        int count = 0;
        page.setCourierNum(Integer.valueOf(id));

        pageExample.createCriteria().andPageIdEqualTo(page.getPageId());
        if(null != page.getStatus()){
            if(userPage.getStatus().equals("已完成")){
                courierWorkExample.createCriteria().andCourierNumEqualTo(Integer.valueOf(id));
                List<CourierWork> courierList = courierService.courierInHowInCome(courierWorkExample);
                CourierWork courierWork  = courierList.get(0);
                int a = courierWork.getCompleteAmount() + Integer.parseInt(userPage.getMoney());
                courierWork.setCompleteAmount(a);
                int countNum = courierService.courierInCome(courierWork,courierWorkExample);

                try{
                    count = courierService.courierUpdate(pageExample,page);
                }catch (Exception e){
                    e.printStackTrace();
                    responseResult.setCode(2);
                    responseResult.setMessage("操作失败");
                    return responseResult;
                }
            }else{
                try{
                    count = courierService.courierUpdate(pageExample,page);
                    System.out.println(count);
                }catch (Exception e){
                    e.printStackTrace();
                    responseResult.setCode(2);
                    responseResult.setMessage("操作失败");
                    return responseResult;
                }
            }
            if(count>0){
                responseResult.setCode(1);
                responseResult.setMessage("操作成功");
                return responseResult;
            }else{
                responseResult.setCode(2);
                responseResult.setMessage("操作失败");
                return responseResult;
            }
        }else{
            responseResult.setCode(2);
            responseResult.setMessage("请求参数异常，请检查运输状态是否为空，登录是否失效");
            return responseResult;
        }

    }
    @RequestMapping("pagePay")
    @ResponseBody
    public ResponseResult pagePay(String id,ResponseResult responseResult, PageExample pageExample,UserPage userPage){
        System.out.println("id====="+id);
        if(null != userPage.getStatus()){
            List<UserPage> userPages = courierService.selectGrabbing(userPage);
            if(userPages.size()>0){
                responseResult.setData(userPages);
                responseResult.setCode(1);
                return responseResult;
            }
        }
        responseResult.setCode(2);
        responseResult.setMessage("暂无未付款订单");
        return responseResult;
    }
    @RequestMapping("userPay")
    public void pay( String WIDbody,String WIDout_trade_no,String WIDtotal_amount,String WIDsubject,UserPage userpage, HttpServletRequest request,HttpServletResponse response)
            throws AlipayApiException, IOException {
        alipayTradePagePayRequest.setNotifyUrl(AppUtil.notify_url);
        alipayTradePagePayRequest.setReturnUrl(AppUtil.return_url);
        //4.设置请求的参数(传递给支付宝的数据)
        alipayTradePagePayRequest.setBizContent(
                "{\"out_trade_no\":\""+ WIDout_trade_no +"\","
                        + "\"total_amount\":\""+ WIDtotal_amount +"\","
                        + "\"subject\":\""+ WIDsubject +"\","
                        + "\"body\":\""+ WIDbody +"\","
                        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //5.发送请求
        String result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
        //6.将响应结果返回给前端
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(result);
    }

    @RequestMapping("/getnotify")
    public void getNotify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        System.out.println("异步通知执行了");
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        Iterator<String> iter = requestParams.keySet().iterator();
        while(iter.hasNext()){
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AppUtil.alipay_public_key, AppUtil.charset, AppUtil.sign_type); //调用SDK验证签名
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(signVerified) {
            String trade_status = request.getParameter("trade_status");
            if(trade_status.equals("TRADE_FINISHED")){

            }else if (trade_status.equals("TRADE_SUCCESS")){
                System.out.println("付款成功");
                PageExample pageExample = new PageExample();
                Page page = new Page();
                String outTradeNo = request.getParameter("out_trade_no");
                String invoiceAmount = request.getParameter("invoice_amount");
                String subject = request.getParameter("subject");
                String body = request.getParameter("body");

                String[] strings = outTradeNo.split("X");

                pageExample.createCriteria().andPageIdEqualTo(Integer.valueOf(strings[1]));
                page.setStatus("待送达");
                int count = courierService.courierUpdate(pageExample,page);
                System.out.println("受影响行数"+count);
            }
        }else {

        }

    }
    @RequestMapping("/getreturn")
    public String getReturn(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        //获取支付宝GET过来反馈信息
        //String strings = "1";
//        return "redirect:http://localhost:8085/courier/html/rush-delivery.html?pageNumSuccess="+strings;
        System.out.println("同步通知执行了");
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        Iterator<String> iter = requestParams.keySet().iterator();
        while(iter.hasNext()){
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        System.out.println(params);
//        timestamp=2020-12-21 16:37:42
        String timestamp = request.getParameter("timestamp");
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AppUtil.alipay_public_key, AppUtil.charset, AppUtil.sign_type); //调用SDK验证签名
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(signVerified) {
            String outTradeNo = request.getParameter("out_trade_no");
            String totalAmount = request.getParameter("total_amount");
            String[] strings = outTradeNo.split("X");

            return "redirect:http://localhost:8085/courier/html/rush-delivery.html?pageNumSuccess="+strings[0]+"&totalAmount="+totalAmount;
        }else {
            out.println("验签失败");
        }
        return "redirect:http://localhost:8085/courier/html/rush-delivery.html";
    }

}
